package main

import(
	"fmt"
	"sync"
	"time"
)

// 计数器
type counter struct {
	num uint // 计数
	mu sync.RWMutex //读写锁
}

// 获取num值的操作，加读锁
func (c *counter) number() uint {
	c.mu.RLock()
	defer c.mu.RUnlock()
	return c.num
}

// 修改num值的操作，加写锁
func (c *counter) add (increment uint) uint {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.num += increment
	return c.num
}

// 跑一下上面的两个方法看看效果
func main() {
	c := counter{}
	done := make(chan struct{})

	// 增加计数器
	go func() {
		defer func() {
			done <- struct{}{}
		}()
		for i := 0; i < 10; i++ {
			time.Sleep(time.Millisecond * 500)
			c.add(1)
		}
	}()

	go func() {
		defer func() {
			done <- struct{}{}
		}()
		for j := 0; j < 20; j++ {
			time.Sleep(time.Millisecond * 200)
			fmt.Printf("[%d-%02d] 读数: %d\n", 1, j, c.number())
		}
	}()

	go func() {
		defer func() {
			done <- struct{}{}
		}()
		for k := 0; k < 20; k++ {
			time.Sleep(time.Millisecond * 300)
			fmt.Printf("[%d-%02d] 读数: %d\n", 2, k, c.number())
		}
	}()

	<- done
	<- done
	<- done
}